package com.gambi.tapestry.services.gwt.internal;

import org.apache.tapestry5.internal.services.LinkSource;
import org.apache.tapestry5.services.ComponentClassResolver;
import org.apache.tapestry5.services.Request;

import com.gambi.tapestry.services.gwt.ServiceTargetLinkSource;
import com.gambi.tapestry.utils.GWTConstant;

public class ServiceTargetLinkSourceImpl implements ServiceTargetLinkSource {

	/*
	 * In this version, GWT end point services are provided via pages, thus we
	 * use the pageRenderLinkSource service as base logic to generate service
	 * links. The same page can ba accessed in "normal way" if one wants to, or
	 * in service endpoint way via the link provided by @this service
	 */
	private final LinkSource LinkSource;
	private final ComponentClassResolver componentClassResolver;
	// Not sure about this 
	private final Request request;
	
	public ServiceTargetLinkSourceImpl(LinkSource LinkSource, Request request, ComponentClassResolver componentClassResolver) {
		this.LinkSource = LinkSource;
		this.request = request;
		this.componentClassResolver = componentClassResolver;
	}

	@Override
	public String createServiceTargetLink(@SuppressWarnings("rawtypes") Class serviceClass) {
		try{
		String logicaPageName = componentClassResolver.resolvePageClassNameToPageName( serviceClass.getName() );
		String appContext = request.getContextPath();

		System.out
				.println("ServiceTargetLinkSourceImpl.createServiceTargetLink() " + appContext + GWTConstant.GWT_REMOTE_SERVICE_PREFIX + "/" + logicaPageName );
		
		return appContext + GWTConstant.GWT_REMOTE_SERVICE_PREFIX + "/" + logicaPageName;
		
		
		} 
		catch (IllegalArgumentException e) {
			throw new RuntimeException( "The provided service target class does not corrispond to any valid page", e );
		}
		catch (Throwable e) {
			throw new RuntimeException( "Generic error" , e );
		}
		
		

	}

}
